﻿using System;
using System.Collections.Generic;
using System.Linq;
using EzDesk.Core.Data;
using EzDesk.Core.Interface;
using EzDesk.Core.Model;
using EzDesk.Apps.Interface;

namespace EzDesk.Core.ServiceImpl.Services
{
    public partial class CoreClientService : ICoreClientService
    {

        #region [ private methods ]
        private IList<AppFunction> getAppFunctionsbyUserAgent(EzDeskUserAgentType userAgent)
        {
            return EzDeskDatabaseContainer.Go(
                container =>
                    {
                        var userAgentStr = userAgent.ToString();
                        var list = container.AppFunctionSet.Where(p => p.UserAgent.Contains(userAgentStr)).ToList();
                        foreach (var appFunction in list)
                        {
                            container.LoadProperty(appFunction, p => p.Type);
                            container.LoadProperty(appFunction, p => p.Category);
                            appFunction.TargetUrl = getTargetUrlFromFuncUrl(appFunction.FuncUrl);
                            appFunction.IconUrl = getIconUrl(appFunction.IconName);
                            appFunction.Type.IconUrl = getIconUrl(appFunction.Type.IconName);
                            appFunction.Category.IconUrl = getIconUrl(appFunction.Category.IconName);
                        }
                        return list;
                    });
        }



        #endregion


        # region [ App Functions ]

        public IList<AppFunction> GetAllAppFunctions(Guid userId)
        {
            EzDeskUserAgentType userAgent = _operationProperties.UserAgent;
            
            // 从数据库中直接读取注册的App功能，同时根据权限等进行处理
            IList<AppFunction> appFunctions = getAppFunctionsbyUserAgent(userAgent);
            IList<AppFunction> appFuntionsToRemove = (from appFunction in appFunctions
                                                      where (!string.IsNullOrEmpty(appFunction.PermissionNeed) && 
                                                        !string.IsNullOrEmpty(appFunction.PermissionNeed.Trim()))
                                                      let permissons = appFunction.PermissionNeed.Split(',')
                                                      let hasPermission = (from permissionStr in permissons
                                                                           where !string.IsNullOrEmpty(permissionStr)
                                                                           select _coreService.UserHasPermission(permissionStr, userId))
                                                                           .All(userHasPermission => userHasPermission)
                                                      where !hasPermission
                                                      select appFunction).ToList();

            // 删除无权限的功能
            foreach (var functionToRemove in appFuntionsToRemove)
            {
                appFunctions.Remove(functionToRemove);
            }

            var result = appFunctions.Select(p =>
            {
                p.TargetUrl = getTargetUrlFromFuncUrl(p.FuncUrl);
                p.IconUrl = getIconUrl(p.IconName);
                return p;
            })
            .ToList();

            return result;
        }




        public string GetAppFunctionShortcutIds(Guid userId)
        {
            return EzDeskDatabaseContainer.Go(
                           container => container.AppFunctionShortcutSet.FirstOrDefault(p => p.UserId == userId)).ShortcutSequence;
        }

        public void UpdateAppFunctionShortcutSequnce(Guid userId, string shortcutIdSequnces)
        {
            // todo: 验证shorcurId的正确性
            EzDeskDatabaseContainer.GoAndSave(
                container =>
                {
                    var shortCut = container.AppFunctionShortcutSet.FirstOrDefault(p => p.UserId == userId);
                    if (shortCut == null)
                    {
                        shortCut = new AppFunctionShortcut()
                        {
                            Id = Guid.NewGuid(),
                            ShortcutSequence = shortcutIdSequnces,
                            UserId = userId,
                        };
                        container.AppFunctionShortcutSet.AddObject(shortCut);
                    }
                    else
                    {
                        shortCut.ShortcutSequence = shortcutIdSequnces;
                    }
                });
        }


        #endregion

        public IList<AppFunctionType> GetAllAppFunctionTypes(Guid userId)
        {
            // todo: 整点缓存来取得功能类型
            var allAppFunctions = GetAllAppFunctions(userId);
            IList<AppFunctionType> result = new List<AppFunctionType>();


            foreach (var appFunction in allAppFunctions)
            {
                if (!result.Contains(appFunction.Type, new AppFunctionTypeComparint()))
                {
                    result.Add(appFunction.Type);
                }
            }
            return result;
        }
        
        public IList<AppFunction> GetAppFunctionsByTypeName(Guid userId, string appFunctionTypeName)
        {
            // todo: 整点缓存来取得功能类型
            var allAppFunctions = GetAllAppFunctions(userId);
            return allAppFunctions.Where(p => p.Type.TypeName == appFunctionTypeName).ToList();
        }

        public IList<AppFunctionType> GetAllAppFunctionCategories(Guid userId)
        {
            // todo: 整点缓存来取得功能类型
            var allAppFunctions = GetAllAppFunctions(userId);
            IList<AppFunctionType> result = new List<AppFunctionType>();


            foreach (var appFunction in allAppFunctions)
            {
                if (!result.Contains(appFunction.Category, new AppFunctionTypeComparint()))
                {
                    result.Add(appFunction.Category);
                }
            }
            return result;
        }
        public IList<AppFunction> GetAppFunctionsByCategoryName(Guid userId, string categoryName)
        {
            var allAppFunctions = GetAllAppFunctions(userId);
            var x= allAppFunctions.Where(p => p.Category.TypeName == categoryName).ToList();
            return x;

        }
    }
}
